import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login'
import Home from './components/Home'
import Welcome from "@/components/Welcome";
import Users from "@/components/user/Users";
import Rights from "@/components/power/Rights";
import Roles from "@/components/power/Roles";
import Cate from "@/components/goods/Cate";

Vue.use(Router)

const router = new Router({
  routes: [
    //  登录页面路由
    {path: '/', redirect: '/login'},
    {path: '/login', component: Login, meta: {title: "首页"}},

    //  Home页面的路由规则
    {
      path: "/home",
      component: Home,
      redirect: '/welcome',
      children: [
        {path: '/welcome', component: Welcome},
        {path: '/users', component: Users},
        {path: '/rights',component: Rights},
        {path: '/roles' , component: Roles},
        {path: '/categories', component: Cate}
      ]
    },
  ]
})

//为路由对象添加beforeEach导航守卫
router.beforeEach((to, from, next) => {
  //如果访问的是登录页，直接放行
  if (to.path == '/login') return next();
  //从sessionStorage 中获取到保存的 token值
  const token = window.sessionStorage.getItem("token");
  //如果没有token，强制跳转到登录页
  if (!token) return next('/login');
  next();
})

export default router